package com.gd.iot.energy.util;


import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;


/**
 * xml文件解析工具
 *
 * @author kris
 */
@Slf4j
public class CustomDomResolveUtil {

    private CustomDomResolveUtil() {
    }

    /**
     * 读取xml
     *
     * @param inputStream 文件路径及名称
     * @return
     */
    public static Element parseXml(InputStream inputStream) {
        // 以文件流作为输入，防止异常时文件流未关闭
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(inputStream);
            return document.getRootElement();
        } catch (DocumentException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return null;
    }

    /**
     * 读取xml
     *
     * @param fileName 文件路径及名称
     * @return
     */
    public static Element parseXml(String fileName) {
        // 以文件流作为输入，防止异常时文件流未关闭
        SAXReader saxReader = new SAXReader();

        try (FileInputStream inputStream = new FileInputStream(fileName)) {

            Document document = saxReader.read(inputStream);
            return document.getRootElement();
        } catch (DocumentException | IOException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 读取xml
     *
     * @param content 文件路径及名称
     * @return
     */
    public static Element parseXmlContent(String content) {
        // 以文件流作为输入，防止异常时文件流未关闭
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(new ByteArrayInputStream(content.getBytes()));
            return document.getRootElement();
        } catch (DocumentException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

}
